import tkinter as tk
import threading
from tidal.tidal import Tidal

class Application(tk.Frame):
  def __init__(self, master = None):
    super().__init__(master)
    self.master = master
    self.pack()
    self.create_widgets()
    self.tidal = Tidal()
    self.logged_in = False

  def download_song(self, song_id):
    print("downloading song %i" % song_id)
    song_index = self.download_list_next
    song_name = song_id
    self.download_list_next = self.download_list_next + 1
    def render(progress = 0):
      progress_percent = '%.2f' % (progress * 100)
      print(song_index)
      self.download_list.delete(song_index)
      self.download_list.insert(song_index, "{}: {}%".format(song_name, progress_percent))
    render()
    track = self.tidal.get_track(song_id)
    song_name = track.title
    def progress_callback(progress):
      render(progress)
    thread = threading.Thread(
      target = track.download,
      args = [self.tidal],
      kwargs = {"progress_callback": progress_callback}
    )
    thread.start()

  def create_widgets(self):
    self.logged_in_text = tk.StringVar()
    tk.Label(self, textvariable = self.logged_in_text).pack()
    self.logged_in_text.set("Not logged in.")

    tk.Label(self, text = "Username").pack()
    self.username_entry = tk.Entry(self)
    self.username_entry.insert(0, "tidalaccount@maildrop.cc")
    self.username_entry.pack()
    tk.Label(self, text = "Password").pack()
    self.password_entry = tk.Entry(self)
    self.password_entry.insert(0, "Tidal1!")
    self.password_entry.pack()
    def login():
      username = self.username_entry.get()
      password = self.password_entry.get()
      data = self.tidal.login(username, password)
      self.logged_in_text.set("Logged in as %s." % data["username"])
      self.logged_in = True
    tk.Button(self, text = "Log in", command = login).pack()

    tk.Label(self, text = "Song ID").pack()
    self.song_id_entry = tk.Entry(self)
    self.song_id_entry.insert(0, "77556058")
    self.song_id_entry.pack()

    def download_song():
      if not self.logged_in:
        return print("not logged in")
      return self.download_song(int(self.song_id_entry.get()))
    self.download_song_button = tk.Button(self, text = "Download song", command = download_song)
    self.download_song_button.pack()

    self.download_list = tk.Listbox(self)
    self.download_list_next = 0
    self.download_list.pack()

  def say_hi(self):
    print("hi there, everyone!")

def main():
  root = tk.Tk()
  app = Application(master = root)
  app.mainloop()
